using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Box2D.XNA;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework;

namespace WindowsPhoneGame1
{
    public class PhysicObject:BaseObject,Focusable
    {
        protected World _world;
        protected Body _body;
        protected Fixture _fixture=null;
        protected Texture2D _texture;
        protected Vector2 _size;
        protected const int PIXEL_TO_METER = 60;

        public PhysicObject(World world) {
            CreatBody(world);
        }

        public virtual void CreatBody(World world) {
            this._world = world;
            BodyDef bodyDef = new BodyDef();
            //bodyDef.type = BodyType.Dynamic;
            bodyDef.position = new Vector2(300/PIXEL_TO_METER, 200/PIXEL_TO_METER);
            _body = world.CreateBody(bodyDef);
            _body._type = BodyType.Dynamic;
            SetSize(new Vector2(20, 20));
            _texture = ResourceManager.LoadTexture("images/mySprite");
        }

        public void SetSize(Vector2 size) {
            this._size = size;

            //if(_fixture!=null)
            //    _body.DestroyFixture(_fixture);

            FixtureDef f = new FixtureDef();
            PolygonShape p = new PolygonShape();
            f.shape = p;
            f.density = 100;
            f.restitution = 0.08f;
            f.friction = 0.5f;
            p.SetAsBox(_size.X / (PIXEL_TO_METER*2), _size.Y / (PIXEL_TO_METER*2));
            this._fixture = _body.CreateFixture(f);
            _body._fixtureList = this._fixture;
        }

        public void SetPostion(Vector2 position) {
            if (this._body == null)
                throw new Exception("null body");
            position.X/=PIXEL_TO_METER;
            position.Y/=PIXEL_TO_METER;
            this._body.SetTransform(position, 0f);
        }

        public override void OnDraw(SpriteBatch spriteBatch)
        {
            //spriteBatch.Begin();
            spriteBatch.Draw(_texture, 
                new Rectangle((int)(_body.Position.X * PIXEL_TO_METER-_size.X/2), 
                    (int)(480-_body.Position.Y * PIXEL_TO_METER-_size.Y/2), 
                  (int)_size.X, (int)_size.Y), Color.White);
            //spriteBatch.End();
        }

        public override void Update(int delta)
        {
          
        }

        public Vector2 Position
        {
            get
            {
                return new Vector2((_body.Position.X * PIXEL_TO_METER - _size.X / 2),
                    (480 - _body.Position.Y * PIXEL_TO_METER - _size.Y / 2));
            }

        } 
    }
}
